<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 方式1：左右布局，通过栅格布局 -->
        <!-- <el-row>
                  <el-col :span="22">left</el-col>
                  <el-col :span="2">right</el-col>
                </el-row>-->
        <!-- 方式2：左右布局，通过flex布局 -->
        <tree-node :data="companyInfo">
          <!-- 点击一级部门 -->
          <el-dropdown-item @click.native="onAdd(companyInfo)">添加子部门</el-dropdown-item>
        </tree-node>
        <el-tree :data="list" :props="{label:'name'}" default-expand-all>
          <template v-slot="{data}">
            <tree-node :data="data">
              <el-dropdown-item @click.native="onAdd(data)">添加子部门</el-dropdown-item>
              <el-dropdown-item @click.native="onUpdate(data.id)">编辑部门</el-dropdown-item>
              <el-dropdown-item @click.native="onDel(data.id)">删除部门</el-dropdown-item>
            </tree-node>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 数据传给子组件 -->
    <add-dept
      :show-dialog.sync="showDialog"
      :node="currentNode"
      @success="getDeparmentsFn"
      ref="addRef"
    ></add-dept>
  </div>
</template>

<script>
import { delDepartments, getDeparments, getDepartmentById } from '@/api/department.js'
import { translateListToTree } from '@/utils'
import TreeNode from './components/tree-node.vue'
import AddDept from './components/add-dept.vue'

export default {
  name: 'DepartmentsPage',
  components: {
    TreeNode,
    AddDept
  },
  props: {},
  data() {
    return {
      showDialog: false, // 控制对话框显示
      companyInfo: { name: 'Department of Company', manager: 'In charge', id: '' },
      list: [],
      currentNode: {} // 当前操作的部门
    }
  },
  created() {
    this.getDeparmentsFn()
  },
  mounted() {
  },
  methods: {
    async getDeparmentsFn() {
      const { depts } = await getDeparments()
      // 调用方法 把数据转换成树形结构
      this.list = translateListToTree(depts, '')
    },
    onAdd(node) {
      console.log('add')
      this.showDialog = true
      this.currentNode = node
    },
    async onUpdate(id) {
      // 获取详情
      const data = await getDepartmentById(id) // 完成数据回显
      console.log('data', data)
      // 数据传到子组件
      // 方式1 - 通过props(不推荐,因为非常麻烦,大家要记住)
      // v-bind/v-model通过属性绑定
      // 方式2 - 通过ref直接通信
      this.$refs.addRef.form = data
      // 打开对话框
      this.showDialog = true
    },
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        // 确认删除
        // 通过代码片段
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        // 点击确定
        await delDepartments(id)
        // 提示成功
        this.$message.success('操作成功')
        // 刷新列表
        this.getDeparmentsFn()
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;

}
</style>

